import 'package:common_utils/common_utils.dart';
import 'package:fate_blind_box/chat_view/audio_message_view.dart';
import 'package:fate_blind_box/chat_view/chat_net_image.dart';
import 'package:fate_blind_box/chat_view/custom_message_view.dart';
import 'package:fate_blind_box/chat_view/image_message_view.dart';
import 'package:fate_blind_box/chat_view/text_message_view.dart';
import 'package:fate_blind_box/chat_view/video_message_data.dart';
import 'package:fate_blind_box/im/entity/chat_group_entity.dart';
import 'package:fate_blind_box/im/person_info.dart';
import 'package:fate_blind_box/model/chat_friend_message_entity.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';

class GroupMessageCell extends StatelessWidget {
  final EMMessage message;
  final EMUserInfo? userInfo;
  final ChatFriendMessageEntity? model;

  const GroupMessageCell({
    super.key,
    required this.message,
    this.userInfo,
    this.model,
  });

  @override
  Widget build(BuildContext context) {
    if (isSystemMessage) {
      return groupMessage();
    } else {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(
            height: 6.w,
          ),
          Center(
              child: Text(
            serverTime,
            style: TextStyle(fontSize: 10, color: ThemeColor.textColorSecond),
          )),
          SizedBox(
            height: 6.w,
          ),
          contentView(),
        ],
      );
    }
  }

  /// 获取消息时间
  String get serverTime {
    var showTime = DateUtil.formatDate(
        DateTime.fromMillisecondsSinceEpoch(
          message.serverTime,
        ),
        format: 'MM月dd日 HH:mm');
    Provider.cache("serverTime", message.serverTime.toString());
    return showTime;
  }

  /// 判断是否是系统消息
  bool get isSystemMessage {
    if (message.body.type == MessageType.CUSTOM) {
      Map json = message.body.toJson();
      if (json['event'] != null && json['event'] == 'addGroup') {
        return true;
      }
    }
    return false;
  }

  /// 群消息
  Widget groupMessage() {
    Map json = message.body.toJson();
    ChatGroupEntity model = ChatGroupEntity.fromJson(json);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          serverTime,
          style: TextStyle(fontSize: 10, color: ThemeColor.textColorSecond),
        ),
        SizedBox(height: 2.w),
        Text.rich(
          TextSpan(text: '欢迎 ', children: [
            TextSpan(
              text: '${model.params?.userName}',
              style: TextStyle(fontSize: 12.sp, color: Colors.blue),
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  Get.to(PersonInfo(sig: model.params?.id));
                },
            ),
            TextSpan(
                text: ' 加入群聊',
                style: TextStyle(
                    fontSize: 12.sp, color: ThemeColor.textColorSecond)),
          ]),
          style: TextStyle(fontSize: 12.sp, color: ThemeColor.textColorSecond),
        ),
      ],
    );
  }

  /// 消息体
  Widget contentView() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      textDirection: message.direction == MessageDirection.SEND
          ? TextDirection.rtl
          : TextDirection.ltr,
      children: [
        headerView(),
        getMessageType(message.body.type),
      ],
    );
  }

  /// 消息头像
  Widget headerView() {
    return InkWell(
      onTap: () => _getMemberInfo(message.from.toString()),
      child: Container(
          margin: EdgeInsets.only(
              left: message.direction == MessageDirection.RECEIVE ? 20.w : 10.w,
              right:
                  message.direction == MessageDirection.RECEIVE ? 10.w : 20.w),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(5.w),
            child: ChatNetImage(
              imageUrl: '${userInfo?.avatarUrl}',
              width: 40.w,
              height: 40.w,
            ),
          )),
    );
  }

  ///
  _getMemberInfo(String from) async {
    final res = await Api.getInstance().getUserInfo(from);
    if (res['code'] == 0) {
      var model = ChatFriendMessageEntity.fromJson(res['data']);
      Get.to(PersonInfo(sig: model.id),
          routeName: PageRouteNames.personInfoPage);
    } else {
      // ThemeSnackBar.show(context, res['msg']);
    }
  }

  /// 根据不同的消息显示不同的 view
  Widget getMessageType(MessageType type) {
    switch (type) {
      case MessageType.TXT:
        EMTextMessageBody textBody = message.body as EMTextMessageBody;
        return TextMessageView(
          message: message,
          messageBody: textBody,
          userInfo: userInfo,
          // model: model,
        );
      case MessageType.VOICE:
        EMVoiceMessageBody voiceMessageBody =
            message.body as EMVoiceMessageBody;
        return AudioMessageView(
          message: message,
          messageBody: voiceMessageBody,
          userInfo: userInfo,
        );
      case MessageType.IMAGE:
        EMImageMessageBody imageBody = message.body as EMImageMessageBody;
        return ImageMessageView(
          messageBody: imageBody,
          message: message,
          userInfo: userInfo,
        );
      case MessageType.VIDEO:
        EMVideoMessageBody videoBody = message.body as EMVideoMessageBody;
        return VideoMessageData(
          videoMessage: videoBody,
          message: message,
          userInfo: userInfo,
        );
      case MessageType.CUSTOM:
        {
          EMCustomMessageBody customMessageBody =
              message.body as EMCustomMessageBody;
          return CustomMessageView(
            message: message,
            customMessageBody: customMessageBody,
            userInfo: userInfo,
          );
        }
      case MessageType.LOCATION:
        // TODO: Handle this case.
        break;
      case MessageType.FILE:
        // TODO: Handle this case.
        break;
      case MessageType.CMD:
        // TODO: Handle this case.
        break;
      case MessageType.COMBINE:
        // TODO: Handle this case.
        break;
    }
    return Container();
  }
}
